package com.keshe.member.controller;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

//import org.apache.shiro.authz.annotation.RequiresPermissions;

import com.keshe.member.entity.UserTokenEntity;
import com.keshe.member.feign.CartFeignService;
import com.keshe.member.service.UserTokenService;
import io.renren.common.utils.R;
//import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;


import com.keshe.member.entity.UserEntity;
import com.keshe.member.service.UserService;
import com.keshe.common.utils.PageUtils;




/**
 *
 *
 * @author yefansijia
 * @email 1121207699@qq.com
 * @date 2023-01-02 13:31:39
 */
@RefreshScope
@RestController
@RequestMapping("member/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private UserTokenService userTokenService;

    //    远程接口
    @Autowired
    CartFeignService cartFeignService;

    /**
     * 用户商城登陆
     */
    @RequestMapping("login")
    //@RequiresPermissions("member:user:update")
    public R login(@RequestBody UserEntity user){
        // 查找数据库中此用户名用户
        UserEntity userEntity = userService.queryByAccount(user.getAccount());

        //账号不存在、密码错误
        // if(user == null || !user.getPassword().equals(new Sha256Hash(form.getPassword(), user.getSalt()).toHex())) {
        if(userEntity == null || !userEntity.getPassword().equals(user.getPassword())){
            return R.error("账号或密码不正确");
        }

        //生成token，并保存到数据库
        R r = userTokenService.createToken(userEntity.getId());
        return R.ok().put("user_token", r).put("mall_user",userEntity);
    }


    /**
     * 列表
     */
    @RequestMapping("/list")
    //@RequiresPermissions("member:user:list")
    public R list(@RequestParam Map<String, Object> params){
        PageUtils page = userService.queryPage(params);

        return R.ok().put("page", page);
    }


    /**
     * 获取个人信息
     */
    @RequestMapping("/info/{id}")
    //@RequiresPermissions("member:user:info")
    public R info(@PathVariable("id") Integer id){
		UserEntity user = userService.getById(id);
        return R.ok().put("user", user);
    }

    /**
     * 注册
     */
    @RequestMapping("/register")
    //@RequiresPermissions("member:user:save")
    public R register(@RequestBody UserEntity user){
        System.out.println("新用户"+user);
        // 设置允许注册个人信息的标志量
        Boolean flag_account =  true; // 允许更新为true
        Boolean flag_phone =  true; // 允许更新为true
        Boolean flag_email =  true; // 允许更新为trues
        String msg1="";
        String msg2="";
        String msg3="";

        // 获取相同用户名用户
        UserEntity accountUser = userService.queryByAccount(user.getAccount());

        // 获取相同邮箱用户
        UserEntity emailUser = userService.queryByEmail(user.getEmail());

        // 获取相同手机号用户
        UserEntity phoneUser = userService.queryByPhone(user.getPhone());

        if(accountUser!=null) {
            flag_account = false;
            msg1 = "用户名已存在！";
        }

        if(emailUser!=null) {
            flag_email = false;
            msg2 = "邮箱已存在！";
        }
        if(phoneUser!=null){
            flag_phone = false;
            msg3 = "手机号已存在！";
        }

        // 允许注册
        if(flag_account && flag_phone && flag_email){
            Date time = new Date();
            user.setName("初始用户名");
            user.setCreated(time);
            user.setUpdated(time);
            userService.save(user);
            UserEntity newUser =  userService.queryByAccount(user.getAccount());
            //生成token，并保存到数据库
            R r = userTokenService.createToken(newUser.getId());
            return R.ok().put("user_token", r).put("mall_user",newUser);
        }else{
            String msg = msg1+msg2+msg3;
            System.out.println(msg);
            return R.error(msg);
        }
    }

    /**
     * 修改个人信息
     */
    @RequestMapping("/save")
    //@RequiresPermissions("member:user:save")
    public R save(@RequestBody UserEntity user){
		userService.save(user);

        return R.ok();
    }

    /**
     * 修改
     */
    @RequestMapping("/update")
    //@RequiresPermissions("member:user:update")
    public R update(@RequestBody UserEntity user) {
        // 设置允许更新个人信息的标志量
        Integer flag = 0; // 允许更新0，邮箱冲突1，手机号冲突2，邮箱手机号均冲突3

        // 获取相同邮箱用户
        UserEntity emailUser = userService.queryByEmail(user.getEmail());

        // 获取相同手机号用户
        UserEntity phoneUser = userService.queryByPhone(user.getPhone());

        if (emailUser != null) {
            if (!emailUser.getId().equals((user.getId()))) {
                flag = 1;
            }
        }
        if (phoneUser != null) {
            if (!phoneUser.getId().equals((user.getId()))) {
                if (flag == 0) {
                    flag = 2;
                } else {
                    flag = 3;
                }
            }
        }

        switch (flag) {
            case 0: {
                // 更新修改个人信息时间
                user.setUpdated(new Date());
                // 更新
                userService.updateById(user);
                return R.ok();
            }
            case 1: {
                return R.error("该邮箱已存在，请更换其它邮箱");
            }
            case 2: {
                return R.error("该手机号已存在，请更换其它手机号");
            }
            case 3: {
                return R.error("该邮箱和手机号已存在，请更换其它邮箱和手机号");
            }
        }
        return R.error("未知错误，请联系管理员");
    }


    /**
     * 删除
     */
    @RequestMapping("/delete")
    //@RequiresPermissions("member:user:delete")
    public R delete(@RequestBody Integer[] ids){
		userService.removeByIds(Arrays.asList(ids));

        return R.ok();
    }

}
